// pages/orderDetail/orderDetail.js
Page({

    /**
     * 页面的初始数据 
     */
    data: {
        status:"",
        webTask:"",
        orderId:"",
        isOrderDone:"",
        isConsumer:true,
        isOrderTaken:false,
        isOrderCanDone:"true",
        markers: [],
        markerIds:[],
        Identity:"",
        myLongtitude:"",
        myLatitude:"",

        counterInfo:{
        },

        carOrderInfo:{
        }
    },

    navigaToChatRoom: function(e){
        wx.navigateTo({
          url: '/pages/chatRoom/chatRoom?openid='+JSON.stringify(this.data.counterInfo.openid)
        })
    },




    
    cancelBut: function(e){
        var that=this
        var pages = getCurrentPages()
        var beforePage = pages[pages.length - 2];
        wx.showModal({
          title:"取消订单",
          content:"是否确定取消订单",
          success(res){
              if(res.confirm){
                wx.request({
                    url: 'http://119.23.252.15:10002/car/cancelOrder',
                    method:"POST",
                    data:{
                        token:wx.getStorageSync('token'),
                        orderId:that.data.orderId
                    },
                    success(res){
                      if(res.data.status==1){
                      wx.navigateBack({
                        delta: 1,
                        success:function(){
                          beforePage.onLoad()
                          wx.showToast({
                            title: '成功取消订单',
                          })
                        }
                      })
                    }
                    else{
                      wx.showToast({
                        title: '取消订单失败',
                      })
                    }
                    }
                  })

              }
              else{
              console.log("取消")
              }
            }
        })
    },

    doneBut: function(e){
        var that=this
        var pages = getCurrentPages()
        var beforePage = pages[pages.length - 2]
        wx.showModal({
          title:"完成订单",
          content:"是否确定完成订单",
          success(res){
              if(res.confirm){
                wx.request({
                  url: 'http://119.23.252.15:10002/car/completeOrder',
                  method:"POST",
                  data:{
                      token:wx.getStorageSync('token'),
                      orderId:that.data.orderId
                  },
                  success(res){
                    if(res.data.status==1){
                    wx.navigateBack({
                      delta: 1,
                      success:function(){
                        beforePage.onLoad()
                        wx.showToast({
                          title: '成功完成订单',
                        })
                      }
                    })
                  }
                  else{
                    wx.showToast({
                      title: '完成订单失败',
                    })
                  }
                  }
                })
              }
              else{
              console.log("取消")
              }
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this

        //创建对象id
        that.mapCtx = wx.createMapContext('MyMap')
        that.mapCtx.moveToLocation()



        that.setData({
          orderId:JSON.parse(options.openid)
        })


        wx.request({
          url: "http://119.23.252.15:10002/car/getOrderInfo",
          method:"POST",
          data:{
              "token":wx.getStorageSync('token'),
              "orderId":JSON.parse(options.openid),
          },
          success(res){
            console.log(res.data)


            if(res.data.data.myIdentity=="servant"){
                console.log("我是"+res.data.data.myIdentity)
                that.setData({
                    isConsumer:false,
                    Identity:"servant"
                })
            } 

            if (res.data.data.orderInfo.status=="订单完成等待顾客付款"||res.data.data.orderInfo.status=="订单取消")
            {
                that.setData({
                    isOrderDone:true
                })
            }

            if(res.data.data.orderInfo.status=="订单未被接单")
            {
              that.setData({
                isOrderCanDone:false
              })
            }


            if(res.data.data.counterInfo!==null){
              that.setData({
                isOrderTaken:true,
                counterInfo:res.data.data.counterInfo,
                orderId:res.data.data.counterInfo.orderId,
              })
            }
              that.setData({
                  status:res.data.data.orderInfo.status,
                  carOrderInfo:res.data.data.orderInfo,
                  Identity:res.data.data.myIdentity,
                  markers:JSON.parse(res.data.data.orderInfo.locationMarkers)
              })

         if(res.data.data.orderInfo.status=="订单进行中"){
               //创建一个webSocket链接
              that.data.webTask= wx.connectSocket({
                url: 'ws://119.23.252.15:10003/car/'+res.data.data.orderInfo.orderId+'/'+res.data.data.counterInfo.myIdentity,
                header:{
                  'content-type': 'application/json'
                },
                success(){                                                                      
                  console.log("链接成功")
                },
                fail(){
                  console.log("链接失败")
                }
              })

              

              // 检测webSocket链接情况
              that.data.webTask.onOpen(()=>{ console.log('链接成功！') ;return true})

              that.data.webTask.onClose(() =>{console.log("close")})

                          // 接受信息
            that.data.webTask.onMessage((res)=>{
              console.log("接收位置信息中")
              console.log(res)
              var resData =  JSON.parse(res.data)
              if(resData.type=="locationMessage"){
                  if(that.data.Identity=="consumer"){
                    console.log("接受位置中")
                    console.log(resData.servantLocation.latitude)
                    console.log(resData.servantLocation.longitude)
                    if(JSON.parse(resData.servantLocation).longitude!==""){
                      var point=[{
                        id:"n",
                        width:40, 
                        height:40,
                        latitude:JSON.parse(resData.consumerLocation).latitude, 
                        longitude:JSON.parse(resData.consumerLocation).longitude,
                        iconPath:"../../icon/consumer.png"
                              }]

                        that.mapCtx.removeMarkers({
                            markerIds:["n"],
                            success(res){
                              console.log(res)
                              console.log("删除位置信息成功")
                            },
                            fail(res){
                              console.log(res)
                              console.log("删除位置信息失败")
                            },
                            
                            })


                        var markers = that.data.markers
                        markers[2]=point[0]
                        that.setData({
                          markers:markers
                        })
                        console.log(that.data.markers)
                        that.mapCtx.addMarkers({
                                markers:that.data.markers,
                                success(res){
                                  console.log(res)
                                  console.log("更新位置信息成功")
                                },
                                fail(){
                                  console.log("更新位置信息失败")
                                }
                            })
            
                            }
                  }

                  else{
                    console.log("接受位置中")
                    console.log(JSON.parse(res.data))
                    console.log(JSON.parse(resData.servantLocation).longitude)
                    if(JSON.parse(resData.consumerLocation).longitude!=""){  
                      console.log(JSON.parse(resData.consumerLocation).longitude)
                    var point=[{
                          id:"n",
                          width:40, 
                          height:40,
                          latitude:JSON.parse(resData.consumerLocation).latitude, 
                          longitude:JSON.parse(resData.consumerLocation).longitude,
                          iconPath:"../../icon/consumer.png"
                                }]

                          that.mapCtx.removeMarkers({
                              markerIds:["n"],
                              success(res){
                                console.log(res)
                                console.log("删除位置信息成功")
                              },
                              fail(res){
                                console.log(res)
                                console.log("删除位置信息失败")
                              },
                              
                              })


                          var markers = that.data.markers
                          markers[2]=point[0]
                          that.setData({
                            markers:markers
                          })
                          console.log(that.data.markers)
                          that.mapCtx.addMarkers({
                                  markers:markers,
                                  success(res){
                                    console.log(res)
                                    console.log("更新位置信息成功")
                                  },
                                  fail(){
                                    console.log("更新位置信息失败")
                                  }
                              })

                      
                    }
          }

      }

    })
  }


    
          }
        })


  
    
    
    },

    onShow(){

      var that = this

      setInterval(res=>{
        if(that.data.webTask!=""&that.data.status=="订单进行中"){
        var msg = ""
        console.log("共享位置中")
          // if(that.data.webTask.onOpen()){
              msg={latitude:myLatitude,longitude:myLongtitude}
              this.data.webTask.send({
                  data:JSON.stringify(msg),
                  success: function(res){
                      console.log("发送位置成功")
                      console.log(JSON.stringify(msg))
                    },
                  fail:function(res){
                      console.log(res)
                      console.log("发送位置失败")
                      console.log(msg)
                  }
              })
          // }


      }
    },15000)


  

      that.mapCtx.addMarkers({
          markers:that.data.markers,
          success(){
              console.log("添加起点成功")
          }
      })

      //开启定位服务
      var myLatitude = ""
      var myLongtitude = ""
      wx.startLocationUpdateBackground({
          success:function(res){
      //位置改变则返回当前位置经纬度       
            wx.onLocationChange(function (result){
           console.log("速度为:"+result.speed+" 经纬"+result.latitude)
           myLatitude=result.latitude
           myLongtitude=result.longitude
          })
                               }
      })
  
  
  
    },

    onUnload(){
      var that = this

      if(that.data.webTask!=""&that.data.status=="订单进行中"){
      that.data.webTask.close({
        success:function(){
          console.log("关闭websocket")
        }
      })
    }
    }

})